# -*- coding: utf-8 -*-

import os, wsgiref.handlers

# Google App Engine imports.
from google.appengine.ext.webapp import util
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

# Force Django to reload its settings.
from django.conf import settings
settings._target = None

# Must set this env var before importing any part of Django
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from datetime import datetime
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.db import Key
from google.appengine.api import users
from django.utils import simplejson
from time import strftime

from baseclass import BaseHandler
from model import Annotation


class AnnotationQuery(BaseHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            email = user.email()
        if self.request.get("email"):
            email = self.request.get("email")        
        try:
            query = db.Query(Annotation)
            if email:
                query.filter("uri =", self.request.get("uri").rstrip("#")).filter("email =", email)
            else:
                query.filter("uri =", self.request.get("uri").rstrip("#"))
            if self.request.get("tagid"):
                query.filter("tagid =", self.request.get("tagid"))
            query.order("-date")
            items = query.fetch(999)
            if items:
                rows = []
                for item in items:
                    html = """<div><p>%(content)s</p><p>by &nbsp; <a href="mailto:%(email)s">%(author)s</a> &nbsp; %(date)s</p></div>""" % {"content": item.content, "author": item.author, "date": strftime("%Y/%m/%d %H:%M:%S", item.date.timetuple()), "email": "anonymous"}
                    # rows += """{"tagid":"%(tagid)s","html":"%(html)s"},""" % {"tagid": item.tagid, "html": html}
                    row = {"tagid": item.tagid, "html": html, "email": item.email, "author": item.author}
                    rows.append(row)
                json = """{'msg': 'ok',
                           'items':%s}""" % simplejson.dumps(rows)
            else:
                json = """{"msg": "Please add your comments..."}"""
        except:
            json = """{"msg": "error"}"""
        self.response.out.write(json)                

class AnnotationList(BaseHandler):
    def get(self):
        try:
            query = db.Query(Annotation)
            query.filter("uri =", self.request.get("uri").rstrip("#")).filter("tagid =", self.request.get("tagid"))
            items = query.fetch(100)
            if items:
                template_values = {"items": items}
            else:
                template_values = {"msg": "not found"}
        except:
            template_values = {"msg": "error"}
        self.outputTemplate(template_values, "annotation_management_view.html")                

class AnnotationManagement(BaseHandler):
    def get(self):
        query = db.Query(Annotation)
        query.order("-date")
        items = query.fetch(100)
        language = self.request.headers['Accept-Language'].split(",")[0]
        #LANGUAGE_CODE = language
        #language = self.request.cookies['django_language']        
        template_values = {"items":items,
                           "django_language": language}
        self.outputTemplate(template_values, "annotation_management_view.html")                
        
class AnnotationModify(BaseHandler):
    def get(self):
        user = users.get_current_user()
        uri = self.request.get("uri").rstrip("#")
        tagid = self.request.get("tagid")
        query = db.Query(Annotation)
        query.filter("uri =", uri).filter("tagid =", tagid)        
        if user:
            query.filter("email =", user.email())
            item = query.get()
            template_values = {"item": item,
                               "uri": uri,
                               "tagid": tagid,
                               "email": user.email(),
                               "author": user.nickname(),
                               "loginurl": users.create_logout_url(self.request.url)}
        else:
            query.filter("email =", "anonymous")
            item = query.get()
            template_values = {"item": item,
                               "uri": self.request.get("uri").rstrip("#"),
                               "tagid": self.request.get("tagid"),                               
                               "loginurl": users.create_login_url(self.request.url)}       
        self.outputTemplate(template_values, "annotation_modify_view.html")
    
    def post(self):
        user = users.get_current_user()
        if user:
            email = user.email()
        else:
            email = "anonymous"
        try:
            query = db.Query(Annotation)
            query.filter("email =", email).filter("uri =", self.request.get("uri")).filter("tagid =", self.request.get("tagid"))
            annotation = query.get()
            if not annotation:
                annotation = Annotation()
                annotation.email = email
                annotation.uri = self.request.get("uri")
                annotation.tagid = self.request.get("tagid")
            annotation.author = self.request.get("author")
            annotation.content = self.request.get("content")
            annotation.rating = int(self.request.get("rating"))            
            annotation.put()
            template_values = {"msg":_("OK")}
        except:
            template_values = {"msg":"error"}
        self.outputTemplate(template_values, "annotation_modify_view.html")        
        
application = webapp.WSGIApplication(
                                     [('/annotation/management', AnnotationManagement),
                                      ('/annotation/modify', AnnotationModify),
                                      ('/annotation/list', AnnotationList),
                                      ('/annotation/query', AnnotationQuery)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
    